window.qForm = window.qForm || {};

window.qForm.initialize = function(){
	//console.debug( 'qForm.initialize!' );
	new iMask( );
	
	var oneOf = {};
	$$('form .one-of').each(function(el,i){
		var vals=el.get('class').split(' ').filter( function(cls){return cls.test(':');} );
		vals=JSON.decode('{'+vals.join(',')+'}');
		if( !vals.oneOf ) return;
		oneOf[vals.oneOf] = oneOf[vals.oneOf] || {};
		oneOf[vals.oneOf][i] = el;
	});
	$each(oneOf,function(els,i){
	$each(els,function(el,i){
		el.addEvents({'blur':function(e){
		$each(els,function(_el,i){
			if( parseFloat( this.value ) == 0 || this.id == _el.id ) { _el.disabled = false; }
			else { _el.disabled = true; _el.value = '0.00'; }
		}.bind(el));
		}})
	});
	});
	
	$$('form.ajax').each(function(el,i){
	new FormValidator.Inline( el.id, {
		'useTitles': false,
		'onFormValidate': function( passed, form, event ) {
			if( !passed ) return;
			event.stop();
			
			var onSuccess = function(jsr){
				$$('div.splash.ajax-loader').destroy();
				if( !jsr ) return;
				jsr = JSON.decode(jsr);
				
				if( !jsr.result ) return;
				if( jsr.result.error )
				{
					return alert( jsr.result.error );
				}
				else if( jsr.result.location )
				{
					if( jsr.result.message ) {
						if( jsr.result.confirm ) { if( !confirm( jsr.result.message + "\n" + 'Завершить?' ) ) return; }
						else { alert( jsr.result.message ); }
					}
					window.location = jsr.result.location;
				}
			};
			
			// todo: kill it
			if( form.hasClass( 'file' ) ) {
				AIM.onSuccess = function(iframe){
					if( !iframe ) return alert( '500!' );
					var jsr = (new Element('div',{'html':iframe})).getFirst().get('html');
					//console.debug( jsr );
					onSuccess( jsr );
					};
				(new Element('div',{'class':'splash ajax-loader big'})).inject($$('body')[0]);
				form.submit( );
				return true;
			}
			
			form = $(form);
			form.set('send',{'headers':{'Accept':'application/json','X-Request':'JSON'},'onSuccess':onSuccess});
			(new Element('div',{'class':'splash ajax-loader big'})).inject($$('body')[0]);
			form.send();
		}
	});
	});
	
	$$('input').addEvent( 'change', function(e){ window.qForm.changed = true; } );
};

window.addEvent('domready',function(){
	if( window.iMask ) window.qForm.initialize( );
});
